/**
 * @see https://leetcode-cn.com/problems/consecutive-numbers-sum/
 * 给定一个正整数 N，试求有多少组连续正整数满足所有数字之和为 N?
 * @param {number} N
 * @return {number}
 */
var consecutiveNumbersSum = function (N) {
  // 计算缓存
  let countedCache = {};
  // 去重复
  let resultMap = {};
  // 递归计算这个整数所有相加的组合
  function sum(d) {
    // 缓存已经计算过的数据，减少计算次数
    if (countedCache[d]) {
      return countedCache[d];
    }
    if(d === 3) {
      return [[1,2]];
    }
    // 从一半开始往下递减计算
    let start = Math.floor(d / 2);
    let group = [];
    while (start >= 1) {
      let dif = d - start;
      let result
      // 已经有一个递增序列了
      if (Math.abs(dif - start) === 1) {
        result = [start, dif];
        countedCache[d] = result;
        if (!resultMap[result.toString()]) {
          group.push(result);
          resultMap[result.toString()] = true;
        }
      }
      if (dif === start) {
        start--;
        continue;
      }
      if (dif > 2) {
        result = sum(dif);
        countedCache[dif] = result;
        if (result.length) {
          // 存在递增序列，则用start值与结果进行比较，判断是否递增
          result = result[0].concat(start);
          if (isIncrease(result)) {
            if (!resultMap[result.toString()]) {
              group.push(result);
              resultMap[result.toString()] = true;
            }
          }
        }
      }
      start--;
    }
    return group;
  }
  let result = sum(N);
  // 去重复
  console.log(countedCache)
  console.log(result)
};

function isIncrease(arr) {
  arr.sort();
  let is = true;
  arr.reduce((prev, next, i, array) => {
    if (next - prev === 1) {
      return next;
    } else {
      is = false;
      array.splice(1)
      return next;
    }
  })
  return is;
}

var consecutiveNumbersSum2 = function(N) {
  let mm = Math.floor(Math.sqrt(N*2))
  let n = 1
  for(let i=2;i<=mm;i++){
      if(((2*N+i-i**2)/(2*i))%1===0){
          // console.log(i,N/i +(1-i)/2)
          n++
      }
  }
  console.log(n)
  return n
};

consecutiveNumbersSum(85);